<template>
  <div class="drools-tool">
    <Breadcrumb />
    
    <div class="tool-header">
      <div class="container">
        <h1>Drools规则生成器</h1>
        <div class="subtitle-group">
          <p class="subtitle">在线生成 Drools 规则文件</p>
        </div>
      </div>
    </div>

    <div class="tool-content">
      <div class="container">
        <div class="conversion-panel">
          <!-- 规则基本信息 -->
          <div class="rule-base-info">
            <h3>规则基本信息</h3>
            <div class="input-group">
              <input 
                v-model="ruleName" 
                class="custom-input" 
                placeholder="规则名称"
              >
              <input 
                v-model="packageName" 
                class="custom-input" 
                placeholder="包名"
              >
            </div>
          </div>

          <!-- 指标列表 -->
          <div class="metrics-list">
            <h3>条件指标
              <button class="action-btn small" @click="addGroup">添加分组</button>
              <button class="action-btn small" @click="addMetric">添加指标</button>
            </h3>
            <div class="metrics-container">
              <template v-for="(item, index) in ruleItems" :key="index">
                <div v-if="'type' in item && item.type === 'group'" class="metric-group">
                  <div class="group-header">
                    <span>分组 {{ index + 1 }}</span>
                    <div class="group-controls">
                      <select 
                        v-if="ruleItems.filter(i => 'type' in i).length > 1 && index < ruleItems.length - 1" 
                        v-model="item.operator" 
                        class="custom-select"
                      >
                        <option value="AND">AND</option>
                        <option value="OR">OR</option>
                      </select>
                      <button class="action-btn small" @click="() => addMetricToGroup(item)">
                        添加指标
                      </button>
                      <button class="delete-btn" @click="() => removeItem(index)">
                        <i class="fas fa-times"></i>
                      </button>
                    </div>
                  </div>
                  <div class="group-content">
                    <template v-for="(subItem, subIndex) in item.items" :key="subIndex">
                      <div class="metric-item">
                        <div class="metric-header">
                          <span>指标 {{ subIndex + 1 }}</span>
                          <button class="delete-btn" @click="() => removeMetric(item, subIndex)">
                            <i class="fas fa-times"></i>
                          </button>
                        </div>
                        <div class="metric-content">
                          <input 
                            v-model="(subItem as Metric).name" 
                            class="custom-input" 
                            placeholder="指标名称"
                          >
                          <select v-model="(subItem as Metric).type" class="custom-select">
                            <option value="number">数值型</option>
                            <option value="string">字符串</option>
                            <option value="boolean">布尔值</option>
                            <option value="date">日期</option>
                          </select>
                          <select v-model="(subItem as Metric).operator" class="custom-select">
                            <option value=">">&gt;</option>
                            <option value=">=">&gt;=</option>
                            <option value="<">&lt;</option>
                            <option value="<=">&lt;=</option>
                            <option value="==">==</option>
                            <option value="!=">!=</option>
                          </select>
                          <input 
                            v-model="(subItem as Metric).value" 
                            class="custom-input" 
                            placeholder="比较值"
                          >
                          <select 
                            v-if="subIndex < item.items.length - 1" 
                            v-model="(subItem as Metric).connector" 
                            class="custom-select"
                          >
                            <option value="AND">AND</option>
                            <option value="OR">OR</option>
                          </select>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
                <div v-else class="metric-item standalone">
                  <div class="metric-header">
                    <span>指标 {{ index + 1 }}</span>
                    <button class="delete-btn" @click="() => removeItem(index)">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                  <div class="metric-content">
                    <input 
                      v-model="(item as Metric).name" 
                      class="custom-input" 
                      placeholder="指标名称"
                    >
                    <select v-model="(item as Metric).type" class="custom-select">
                      <option value="number">数值型</option>
                      <option value="string">字符串</option>
                      <option value="boolean">布尔值</option>
                      <option value="date">日期</option>
                    </select>
                    <select v-model="(item as Metric).operator" class="custom-select">
                      <option value=">">&gt;</option>
                      <option value=">=">&gt;=</option>
                      <option value="<">&lt;</option>
                      <option value="<=">&lt;=</option>
                      <option value="==">==</option>
                      <option value="!=">!=</option>
                    </select>
                    <input 
                      v-model="(item as Metric).value" 
                      class="custom-input" 
                      placeholder="比较值"
                    >
                    <select 
                      v-if="index < ruleItems.length - 1" 
                      v-model="(item as Metric).connector" 
                      class="custom-select"
                    >
                      <option value="AND">AND</option>
                      <option value="OR">OR</option>
                    </select>
                  </div>
                </div>
              </template>
            </div>
          </div>

          <!-- 结果动作 -->
          <div class="action-section">
            <h3>结果动作</h3>
            <div class="action-content">
              <input 
                v-model="resultAction" 
                class="custom-input" 
                placeholder="输入结果动作..."
              >
            </div>
          </div>

          <!-- 生成按钮 -->
          <div class="generate-section">
            <button class="action-btn" @click="generateRule">生成规则</button>
          </div>

          <!-- 生成的��则 -->
          <div v-if="generatedRule" class="generated-rule">
            <h3>生成的规则
              <button 
                class="action-btn small" 
                @click="copyRule"
                :disabled="copySuccess"
              >
                {{ copySuccess ? '复制成功' : '复制规则' }}
              </button>
            </h3>
            <pre><code>{{ generatedRule }}</code></pre>
          </div>

          <!-- 添加测试区域 -->
          <div v-if="generatedRule" class="test-section">
            <h3>规则测试</h3>
            <div class="test-input">
              <textarea 
                v-model="testJsonData" 
                class="custom-input" 
                placeholder="输入测试用的 JSON 数据..."
                rows="5"
              ></textarea>
            </div>
            <div class="test-actions">
              <button class="action-btn" @click="testRule">测试规则</button>
            </div>
            <div v-if="testResult" class="test-result">
              <h4>测试结果</h4>
              <pre><code>{{ testResult }}</code></pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Breadcrumb from '@/components/Breadcrumb.vue'

interface Metric {
  name: string
  type: 'number' | 'string' | 'boolean' | 'date'
  operator: '>' | '>=' | '<' | '<=' | '==' | '!='
  value: string
  connector?: 'AND' | 'OR'
}

interface MetricGroup {
  type: 'group'
  operator: 'AND' | 'OR'
  items: (Metric | MetricGroup)[]
}

type RuleItem = Metric | MetricGroup

const ruleName = ref('')
const packageName = ref('')
const ruleItems = ref<RuleItem[]>([])
const resultAction = ref('')
const generatedRule = ref('')

// 添加复制成功状态
const copySuccess = ref(false)

// 添加分组
const addGroup = () => {
  const newGroup: MetricGroup = {
    type: 'group',
    operator: 'AND',
    items: []
  }
  ruleItems.value.push(newGroup)
}

// 添加指标
const addMetric = () => {
  const newMetric: Metric = {
    name: '',
    type: 'number',
    operator: '>',
    value: '',
    connector: 'AND'
  }
  ruleItems.value.push(newMetric)
}

// 添加新的函数用于向分组添加指标
const addMetricToGroup = (group: MetricGroup) => {
  if ('type' in group && group.type === 'group') {
    const newMetric: Metric = {
      name: '',
      type: 'number',
      operator: '>',
      value: '',
      connector: 'AND'
    }
    group.items.push(newMetric)
  }
}

// 删除目（指标或分组）
const removeItem = (index: number) => {
  ruleItems.value.splice(index, 1)
}

// 修改生成规则的函数
const generateRule = () => {
  if (!ruleName.value || !packageName.value || ruleItems.value.length === 0 || !resultAction.value) {
    alert('请填写完整信息')
    return
  }

  let rule = `package ${packageName.value};\n\n`
  rule += `import com.alibaba.fastjson.JSONObject;\n\n`
  rule += `rule "${ruleName.value}"\n`
  rule += `when\n`
  rule += `  $json: JSONObject(\n`  // 添加 $json: JSONObject 声明
  
  // 构建条件
  const buildConditions = (items: (Metric | MetricGroup)[], level = 1): string => {
    const indent = '  '.repeat(level + 1)  // 增加缩进级别
    return items.map((item, index) => {
      if ('type' in item && item.type === 'group') {
        const groupConditions = buildConditions(item.items, level + 1)
        const groupConnector = index < items.length - 1 
          ? ` ${item.operator === 'AND' ? '&&' : '||'}` 
          : ''
        return `${indent}(\n${groupConditions}\n${indent})${groupConnector}`
      } else {
        let condition = buildJsonCondition(item)
        if (index < items.length - 1) {
          condition += ` ${item.connector === 'AND' ? '&&' : '||'}`
        }
        return `${indent}${condition}`
      }
    }).join('\n')
  }

  // 修改 JSON 条件构建
  const buildJsonCondition = (metric: Metric): string => {
    let getValue = ''
    switch (metric.type) {
      case 'number':
        getValue = `getDoubleValue("${metric.name}")`
        break
      case 'string':
        getValue = `getString("${metric.name}")`
        break
      case 'boolean':
        getValue = `getBooleanValue("${metric.name}")`
        break
      case 'date':
        getValue = `getString("${metric.name}")`
        break
    }

    let compareValue = metric.value
    if (metric.type === 'string' || metric.type === 'date') {
      compareValue = `"${metric.value}"`
    }

    return `${getValue} ${metric.operator} ${compareValue}`
  }
  
  rule += buildConditions(ruleItems.value)
  rule += `\n  )\n`  // 闭合 JSONObject 条件
  rule += `then\n`
  rule += `  $json.put("result", "${resultAction.value}");\n`
  rule += `end`
  
  generatedRule.value = rule
}

// 修改复制规则函数
const copyRule = async () => {
  try {
    await navigator.clipboard.writeText(generatedRule.value)
    copySuccess.value = true
    setTimeout(() => {
      copySuccess.value = false
    }, 3000)
  } catch (err) {
    console.error('复制失败:', err)
  }
}

// 删除指标的方法
const removeMetric = (group: MetricGroup, index: number) => {
  if ('type' in group && group.type === 'group' && Array.isArray(group.items)) {
    group.items.splice(index, 1)
  }
}

const testJsonData = ref('')
const testResult = ref('')

// 添加测试规则的函数
const testRule = async () => {
  try {
    // 验证输入
    if (!testJsonData.value) {
      alert('请输入测试数据')
      return
    }

    // 验证 JSON 格式
    try {
      JSON.parse(testJsonData.value)
    } catch (e) {
      alert('请输入有效的 JSON 数据')
      return
    }

    // 发送请求到后端
    const response = await fetch('/api/drools/execute', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ruleContent: generatedRule.value,
        jsonData: testJsonData.value
      })
    })

    if (!response.ok) {
      throw new Error('规则执行失败')
    }

    const result = await response.text()
    testResult.value = JSON.stringify(JSON.parse(result), null, 2)
  } catch (error: any) {
    console.error('测试失败:', error)
    alert('测试失败: ' + (error.message || '未知错误'))
  }
}
</script>

<style scoped lang="scss">
.drools-tool {
  .tool-header {
    background: linear-gradient(135deg, var(--primary-color), var(--hover-color));
    padding: 20px 0;
    color: white;
    text-align: center;
    margin-top: -1px;

    h1 {
      font-size: 1.8rem;
      margin-bottom: 0.5rem;
    }

    .subtitle-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: center;

      .subtitle {
        font-size: 0.95rem;
        opacity: 0.9;
        background: rgba(255, 255, 255, 0.1);
        padding: 6px 16px;
        border-radius: 20px;
        backdrop-filter: blur(10px);
      }
    }
  }

  .tool-content {
    padding: 40px 0;

    .conversion-panel {
      background: white;
      border-radius: 12px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      padding: 30px;
      display: flex;
      flex-direction: column;
      gap: 40px;

      // 规则基本信息
      .rule-base-info {
        h3 {
          font-size: 1.2rem;
          margin-bottom: 20px;
          color: var(--text-color);
          display: flex;
          align-items: center;
          gap: 8px;

          &::before {
            content: '';
            width: 4px;
            height: 20px;
            background: var(--primary-color);
            border-radius: 2px;
          }
        }

        .input-group {
          display: flex;
          gap: 20px;
          
          .custom-input {
            flex: 1;
          }
        }
      }

      // 指标列表
      .metrics-container {
        display: flex;
        flex-direction: column;
        gap: 24px;
      }

      // 指标组样式
      .metric-group {
        background: #f8f9fa;
        border-radius: 12px;
        padding: 24px;
        border: 2px solid #eef0f2;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.02);
        margin-left: 20px;
        border-left: 3px solid var(--primary-color);
        
        &::before {
          content: '';
          position: absolute;
          left: -20px;
          top: 50%;
          width: 20px;
          height: 2px;
          background: var(--primary-color);
        }

        &:hover {
          border-color: var(--primary-color);
          box-shadow: 0 4px 12px rgba(0,0,0,0.08);
          transform: translateY(-2px);
        }

        .group-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24px;
          padding-bottom: 16px;
          border-bottom: 2px solid #eef0f2;

          span {
            font-weight: 600;
            color: var(--text-color);
            font-size: 1.1rem;
          }

          .group-controls {
            display: flex;
            gap: 12px;
            align-items: center;
          }
        }

        .group-content {
          padding-left: 24px;
          border-left: 3px solid var(--primary-color);
          background: white;
          border-radius: 12px;
          padding: 20px;
        }
      }

      // 指标项样式
      .metric-item {
        background: white;
        border-radius: 12px;
        padding: 24px;
        border: 2px solid #eef0f2;
        transition: all 0.3s ease;
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        &:hover {
          border-color: var(--primary-color);
          box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .metric-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;

          span {
            font-weight: 500;
            color: var(--text-color);
            font-size: 1.05rem;
          }

          .delete-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            padding: 0;
            border: 2px solid #eef0f2;
            background: white;
            color: #666;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);

            i {
              font-size: 0.9rem;
              transition: all 0.2s ease;
            }

            &:hover {
              border-color: #dc3545;
              background: #dc3545;
              color: white;
              transform: translateY(-1px);
              box-shadow: 0 4px 8px rgba(220, 53, 69, 0.2);

              i {
                transform: rotate(90deg);
              }
            }

            &:active {
              transform: translateY(0);
              box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            }
          }
        }

        .metric-content {
          display: flex;
          gap: 16px;
          align-items: center;
          flex-wrap: wrap;
        }
      }

      // 输入框和选择框统一样式
      .custom-input, .custom-select {
        padding: 12px 16px;
        border: 2px solid #eef0f2;
        border-radius: 8px;
        font-size: 0.95rem;
        transition: all 0.2s ease;
        background: white;

        &:focus {
          outline: none;
          border-color: var(--primary-color);
          box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.1);
        }

        &::placeholder {
          color: #aab0b7;
        }
      }

      .custom-input {
        flex: 1;
        min-width: 150px;
      }

      .custom-select {
        min-width: 120px;
        cursor: pointer;
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%23666' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 12px center;
        padding-right: 32px;
      }

      // 按钮样式统一
      .action-btn {
        min-width: 90px;
        padding: 10px 20px;
        border: none;
        background: var(--primary-color);
        color: white;
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);

        &:hover {
          background: var(--hover-color);
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }

        &.small {
          padding: 8px 16px;
          min-width: auto;
          font-size: 0.9rem;
          margin-left: 12px;
        }

        &:disabled {
          background: #4CAF50;
          cursor: default;
          transform: none;

          &:hover {
            background: #4CAF50;
            transform: none;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
          }
        }
      }

      // 生成的规则样式
      .generated-rule {
        margin-top: 20px;
        background: #f8f9fa;
        border-radius: 12px;
        padding: 24px;

        h3 {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          font-size: 1.1rem;
        }

        pre {
          background: white;
          padding: 24px;
          border-radius: 12px;
          overflow-x: auto;
          font-family: 'Fira Code', monospace;
          font-size: 0.95rem;
          border: 2px solid #eef0f2;
          line-height: 1.6;
          
          code {
            color: #333;
          }
        }
      }

      .test-section {
        margin-top: 30px;
        padding: 24px;
        background: #f8f9fa;
        border-radius: 12px;

        h3 {
          margin-bottom: 20px;
          color: var(--text-color);
        }

        .test-input {
          margin-bottom: 20px;

          textarea {
            width: 100%;
            min-height: 120px;
            resize: vertical;
          }
        }

        .test-result {
          margin-top: 20px;

          h4 {
            margin-bottom: 12px;
            color: var(--text-color);
          }

          pre {
            background: white;
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
          }
        }
      }
    }
  }
}
</style> 